## --------------------------------------------------
## Paths
## --------------------------------------------------

## Job arguments:
## 1) Number of cores to parallelize over
argin <- commandArgs()  ## Grab the job arguments
arg <- argin[(which(argin=="--args")+1):length(argin)]
tag <- arg[1]
begin <- as.numeric(arg[2])
end <- as.numeric(arg[3])
jobNum <- as.numeric(arg[4])
jobTot <- as.numeric(arg[5])
parSeed <- as.numeric(arg[6:11])

print("--------------------")
print(paste("Job:",tag))
print(paste("Begin:", begin))
print(paste("End:", end))
print("--------------------")

load(paste(tag,"common.Rdata", sep="-"))
attach(commonEnv); attach(commonData)

.libPaths(libPaths)
for(pkg in packages){ require(pkg, character.only=TRUE)}
qseed(jobNum=jobNum, jobTot=jobTot, parSeed=parSeed)

outVec <- vector(length=end-begin, mode="list")
counter <- 0
for(i in begin:end){
  counter <- counter + 1
  if( is.null(fargs) ){
    outVec[[counter]] <- FUN(X[[i]])
  }else{
    Xobj <- X[[i]]
    outVec[[counter]] <- 
    do.call(FUN, args=as.list(c(parse(text=paste(names(formals(FUN))[1], "= Xobj")),
                 fargs))) }
}
dir.create(file.path(getwd(), "out", tag), recursive=TRUE)

save( outVec, file=file.path(getwd(), "out", tag, paste('outVec-', begin, '-', end, '.Robj', sep='') ))
